import { useState, useCallback, useEffect, useRef } from 'react';
import styles from './index.module.scss';
import {
  RadioGroup,
  Radio,
  Button,
  Image,
  Card,
  Avatar,
  CardGroup,
  Modal,
  TextArea,
  AudioPlayer,
} from '@douyinfe/semi-ui';
import { IconPlus } from '@douyinfe/semi-icons';
import { Input, Message } from '@arco-design/web-react';
import { ICON_PATHS } from '@/assets/images/constants';
import MlsAudio from '@/components/common/mlsAudio';
import { showConfirmModal } from '@/components/common/mlsModal/modalUtils';
import ScrollingText from '@/components/common/scrollingText';
import MlsModal from '@/components/common/mlsModal';
import MlsUpload from '@/components/common/mlsUpload';
import { timbreAdd, timbreListGet, timbreDelete } from '@/api/audio';
import sharedWebSocket from '@/services/sharedWebSocket.jsx';
import { useLoading } from '@/components/common/mlsLoading/laodingText';

const FILTER_TYPE = [
  {
    label: '全部',
    value: 'all',
  },
  {
    label: '男声',
    value: 'bs',
  },
  {
    label: '女声',
    value: 'gs',
  },
  {
    label: '男童',
    value: 'bc',
  },
  {
    label: '女童',
    value: 'gc',
  },
  {
    label: '其他',
    value: 'other',
  },
];
const VOICE_TYPE = [
  {
    label: '男声',
    value: 'bs',
  },
  {
    label: '女声',
    value: 'gs',
  },
  {
    label: '男童',
    value: 'bc',
  },
  {
    label: '女童',
    value: 'gc',
  },
  {
    label: '其他',
    value: 'other',
  },
];
export default function SoundBank() {
  const [demandType, setDemandType] = useState(1);
  const [filterType, setFilterType] = useState('全部');
  // 添加选中卡片索引状态
  const [selectedCardIndex, setSelectedCardIndex] = useState(-1);
  const [selectedCardData, setSelectedCardData] = useState({});
  const [modalVisible, setModalVisible] = useState(false);
  const [voiceType, setVoiceType] = useState('男声');

  const [uploadAudioFileList, setUploadAudioFileList] = useState([]);
  const [avatarUrl, setAvatarUrl] = useState('');
  const [voiceName, setVoiceName] = useState('');
  const [scriptText, setScriptText] = useState('');
  const [voiceList, setVoiceList] = useState([]);

  const { showLoading, hideLoading } = useLoading();

  const handleDemandTypeChange = useCallback(
    e => {
      const newValue = e.target.value || 1;
      setDemandType(newValue);
      setFilterType('全部');
      setSelectedCardIndex(-1);
      setSelectedCardData({});
    },
    [setDemandType, setFilterType, setSelectedCardIndex, setSelectedCardData]
  );

  // 添加筛选类型变更处理函数
  const handleFilterTypeChange = useCallback(value => {
    setFilterType(value);
    setSelectedCardIndex(-1);
    setSelectedCardData({});
    console.log('filterType', value);
  }, []);

  // 添加卡片选中处理函数
  const handleCardSelect = useCallback((index, item) => {
    setSelectedCardIndex(index);
    setSelectedCardData(item);
  }, []);

  const getList = useCallback(({ filterType, isCustom = false }) => {
    let obj = {
      cate: filterType === '全部' ? '' : filterType,
      isCustom,
      pageNum: 1,
      pageSize: 100000,
    };
    timbreListGet(obj)
      .then(res => {
        if (res.code === 200) {
          setVoiceList(res.data.timbreList || []);
        }
      })
      .finally(() => {
        hideLoading();
      });
  }, []);

  // 添加删除卡片处理函数
  const handleDelete = useCallback(
    (e, index) => {
      e.stopPropagation();
      // 检查是否有选中的卡片
      if (index === -1) {
        showConfirmModal({
          content: '请先选择要删除的音色',
          okButtonProps: {
            style: { display: 'none' },
          },
          modalProps: {
            height: 321,
          },
        });
        return;
      }
      showConfirmModal({
        content: '删除当前音色？',
        okText: '删除',
        modalProps: {
          height: 321,
        },
        type: 'error',
        onOk: () => {
          // 处理删除逻辑
          console.log(`删除  条数据`, voiceList[index]);
          // 调用删除接口
          showLoading('删除中...');
          timbreDelete({
            timbreId: voiceList[index]?.id,
          })
            .then(res => {
              if (res.code === 200) {
                // 删除成功后刷新列表
                // 删除后清除选中状态
                setSelectedCardIndex(-1);
                setSelectedCardData({});
                getList({ filterType, isCustom: true });
              }
            })
            .finally(() => {
              hideLoading();
            });
        },
      });
    },
    [voiceList, filterType, getList, showLoading, hideLoading]
  );

  // 添加筛选类型变更处理函数
  const handleTypeChange = useCallback(value => {
    setVoiceType(value);
    console.log('voiceType', value);
  }, []);

  const fileSuccess = useCallback((result, file) => {
    console.log('fileSuccess', result, file);
    const obj = {
      name: file.name,
      url: result.url,
      size: file.size,
    };
    setUploadAudioFileList([obj]);
  }, []);
  const fileUploadError = useCallback(({ file, error }) => {
    console.log('fileUploadError', file, error);
  }, []);

  const handleDeleteAudio = useCallback((action, url) => {
    setUploadAudioFileList(prev => prev.filter((item, i) => item.url !== url));
  }, []);

  const renderModalContent = () => {
    return (
      <div className={styles.addModalContent}>
        <div className={styles.addModalHeader}>
          <div className={styles.avatarBox}>
            {avatarUrl && (
              <div className={styles.avatarContent}>
                <Avatar className={styles.vocieAvatar} src={avatarUrl} />
                <div className={styles.mask}>
                  <Image
                    alt="删除"
                    title="删除"
                    className={styles.avatarDeleteIcon}
                    src={ICON_PATHS.DELETE_ICON}
                    draggable={false}
                    preview={false}
                    onClick={() => setAvatarUrl('')}
                  />
                </div>
              </div>
            )}
            <MlsUpload
              className={styles.uploadBox}
              accept="image/*"
              onSuccess={(result, file) => {
                setAvatarUrl(result.url);
              }}
              children={() => (
                <Image
                  className={styles.uploadIcon}
                  src={ICON_PATHS.AVATAR_UPLOAD_ICON}
                  draggable={false}
                  preview={false}
                />
              )}
            />
          </div>
          <div className={styles.addConfig}>
            <div className={styles.addvocieTitle}>音色名称</div>
            <Input
              value={voiceName}
              onChange={setVoiceName}
              className={styles.voiceNameInput}
              placeholder="请输入音色名称..."
            />
            <div className={styles.voiceType}>
              <span className={styles.voiceTypeTitle}>音色类型</span>
              {VOICE_TYPE.map(item => (
                <Button
                  className={`${styles.typeBtn} ${
                    voiceType === item.label ? styles.typeBtnActive : ''
                  }`}
                  key={item.label}
                  onClick={() => handleTypeChange(item.label)}>
                  {item.label}
                </Button>
              ))}
            </div>
          </div>
        </div>
        <div className={styles.textereaBox}>
          <span className={styles.voiceDescTitle}>剧本文件</span>
          <div className={styles.voiceDescTextareaBox}>
            <TextArea
              autosize
              maxCount={200}
              value={scriptText}
              onChange={setScriptText}
              className={styles.voiceDescTextarea}
              placeholder="请输入文字即可合成语音..."
            />
          </div>
        </div>
        {/* <AudioUploadComponent title="上传音频" subtitle={''} /> */}
        <div className={styles.audioFooter}>
          <MlsUpload
            action="/dk/v1/fileTransfer/uploader"
            accept="audio/*"
            maxSize={800}
            onSuccess={(result, file) => fileSuccess(result, file)}
            onError={(error, file) => fileUploadError({ file, error })}></MlsUpload>

          {uploadAudioFileList[0] && (
            <div className={styles.voiceAudio}>
              <MlsAudio
                mode
                src={uploadAudioFileList[0]?.url}
                title={uploadAudioFileList[0]?.name}
                showVolumeControl={false}
                onOtherAction={handleDeleteAudio}></MlsAudio>
            </div>
          )}
        </div>

        {/* {uploadAudioFileList[0] && <AudioPlayer autoPlay={false} theme='light' audioUrl={uploadAudioFileList[0]?.url} showToolbar={false} />} */}
      </div>
    );
  };

  const closeModal = useCallback(() => {
    setVoiceType('男声');
    setModalVisible(false);
    setVoiceName('');
    setScriptText('');
    setUploadAudioFileList([]);
    setAvatarUrl('');
  }, []);

  const addVoice = useCallback(() => {
    const timbreName = voiceName;
    const timbreCate = voiceType;
    const text = scriptText;
    const referenceAudioUrl = uploadAudioFileList[0]?.url;
    const imgUrl = avatarUrl;
    if (!timbreName || !timbreCate || !text || !referenceAudioUrl || !imgUrl) {
      Message.error('请填写完整信息');
      return;
    }
    const data = {
      timbreName,
      timbreCate,
      text,
      referenceAudioUrl,
      imgUrl,
      audioText: uploadAudioFileList[0]?.name,
    };
    showLoading('新增中...');
    timbreAdd(data)
      .then(res => {
        if (res.code === 200) {
          closeModal();
        }
      })
      .catch(err => {
        console.log('err', err);
        Message.error('新增失败');
      });
    setModalVisible(false);
  }, [voiceType, uploadAudioFileList, avatarUrl, voiceName, scriptText]);

  // 添加：页面加载时自动查询数据
  useEffect(() => {
    // 根据demandType决定查询类型
    if (demandType === 1) {
      // 预设音色
      showLoading('加载中...');
      getList({ filterType, isCustom: false });
    } else {
      // 自定义音色
      showLoading('加载中...');
      getList({ filterType, isCustom: true });
    }
  }, [demandType, filterType]);

  useEffect(() => {
    const handleOpt = data => {
      console.log('socket---', data);
      if (data?.func === 'add_timbre_success') {
        // 再去查询列表
        getList({ filterType, isCustom: true });
      }
      if (data?.func === 'add_timbre_fail') {
        Message.error(data?.message || '添加音色失败');
        hideLoading();
      }
    };

    sharedWebSocket.on('resp', handleOpt);
    return () => {
      sharedWebSocket.off('resp', handleOpt);
    };
  }, [filterType]);

  return (
    <div className={styles.soundBank}>
      <div className={styles.topToolColumn}>
        <div className={styles.typeTab}>
          <RadioGroup
            type="button"
            buttonSize="small"
            className={styles.typeGroup}
            value={demandType}
            onChange={handleDemandTypeChange}>
            <Radio value={1}>
              <div className={styles.typeItem}>预设音色</div>
            </Radio>
            <Radio value={2}>
              <div className={styles.typeItem}>自定义</div>
            </Radio>
          </RadioGroup>
        </div>
        <div className={styles.filterBox}>
          <span>筛选</span>

          {FILTER_TYPE.map(item => (
            <Button
              className={`${styles.filterBtn} ${
                filterType === item.label ? styles.filterBtnActive : ''
              }`}
              key={item.label}
              onClick={() => handleFilterTypeChange(item.label)}>
              {item.label}
            </Button>
          ))}
          {demandType === 2 && (
            <>
              <Button
                icon={<IconPlus />}
                className={`${styles.filterBtn} ${styles.addBtn} buttonPrimary`}
                onClick={() => setModalVisible(true)}>
                添加音色
              </Button>
              <Button
                className={`${styles.filterBtn} ${styles.deleteBtn}`}
                onClick={e => handleDelete(e, selectedCardIndex)}>
                <Image
                  className={styles.deleteIcon}
                  width={16}
                  src={ICON_PATHS.DELETE_ICON}
                  draggable={false}
                  preview={false}
                />
                删除
              </Button>
            </>
          )}
        </div>
      </div>
      <div className={styles.soundListBox}>
        <CardGroup spacing={14}>
          {voiceList.map((item, index) => (
            <Card
              className={`${styles.soundCardItem} ${
                selectedCardIndex === index ? styles.cardSelected : ''
              }`}
              key={item.id}
              shadows="hover"
              onClick={() => handleCardSelect(index, item)}>
              <Avatar src={item.imgUrl} className={styles.soundAvatar} />
              {/* <span className={styles.soundName}>成熟稳重高冷深邃-男声</span> */}
              {/* <div
                className={styles.soundNameContainer}
                ref={el => (textContainerRefs.current[index] = el)}
                data-overflow={textOverflowStates[index] ? 'true' : 'false'}>
                <span className={styles.soundNameText}>{item.name}</span>
              </div> */}
              <ScrollingText
                text={item.name}
                width={90}
                height={22}
                speed={4}
                gapDistance={10}
                // className={styles.soundNameContainer}
              />
              {demandType === 2 && (
                <div className={styles.moreIcon} onClick={e => handleDelete(e, index)}>
                  <Image
                    // className={styles.moreIcon}
                    width={20}
                    src={ICON_PATHS.SOUND_DELETE_ICON}
                    draggable={false}
                    preview={false}
                  />
                </div>
              )}
            </Card>
          ))}
        </CardGroup>
      </div>
      {selectedCardIndex !== -1 && (
        <div className={styles.soundPlayer}>
          <Avatar src={selectedCardData?.imgUrl} className={styles.footerAvatar} />
          {/* <p title={voiceList[selectedCardIndex]} className={styles.footerAudioName}>
            {voiceList[selectedCardIndex]}
          </p> */}
          <ScrollingText
            text={selectedCardData?.name}
            width={90}
            height={24}
            speed={4}
            gapDistance={10}
            className={styles.footerAudioName}
          />
          <MlsAudio
            src={selectedCardData?.voiceUrl}
            title={selectedCardData.name}
            showVolumeControl={false}
            showELseControl={false}
            showTitle={false}
          />
        </div>
      )}

      <MlsModal
        visible={modalVisible}
        onCancel={closeModal}
        onConfirm={addVoice}
        title="添加音色"
        modalProps={{
          maskClosable: false,
          width: 768,
          height: 620,
          className: `custom-semi-modal-style ${styles.addModal}`,
        }}
        children={renderModalContent()}
      />
    </div>
  );
}
